<template>
  <div class="officialStaffBox">
    <div class="title">正式员工管理</div>
    <div class="btn">
      <el-input v-model="staffInput" placeholder="请输入员工姓名" clearable class="input-with-select" @change="changeStaffName" @input="changeInput">
        <el-button slot="append" type="primary" icon="el-icon-search" @click="changeStaffName" >搜索</el-button>
      </el-input>
      <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增员工</el-button>
      <el-button type="primary" @click="batchDelete" class="batchDelete">批量删除</el-button>
      <el-date-picker
        v-model="dateTime"
        type="daterange"
        unlink-panels
        range-separator="至"
        start-placeholder="入职日期"
        end-placeholder="入职日期"
        :picker-options="pickerOptions"
        @change="searchDate"
        >
      </el-date-picker>
      <!-- <el-button  type="primary" icon="el-icon-search" @click="searchDate">搜索</el-button> -->
      <!-- 弹出框modal -->
      <el-dialog :title="modalTitle" center width="50%" :visible.sync="StaffVisible" @close="cancel">
        <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="姓名" prop="name" >
            <el-input v-model="ruleForm.name" style="width:300px"></el-input>
          </el-form-item>
          <el-form-item label="年龄" prop="age">
            <el-input v-model="ruleForm.age" oninput = "value=value.replace(/[^\d]/g,'')" style="width:300px"></el-input>
          </el-form-item>
          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="ruleForm.gender">
              <el-radio label="男"></el-radio>
              <el-radio label="女"></el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="电话号码" prop="phone">
            <el-input v-model="ruleForm.phone" oninput = "value=value.replace(/[^\d]/g,'')" style="width:300px"></el-input>
          </el-form-item>
          <el-form-item label="家庭住址" prop="address">
            <el-input v-model="ruleForm.address" style="width:300px"></el-input>
          </el-form-item>
          <el-form-item label="职位" prop="duty">
            <el-input v-model="ruleForm.duty" style="width:300px"></el-input>
          </el-form-item>
          <el-form-item label="薪资" prop="salary">
            <el-input v-model="ruleForm.salary" oninput = "value=value.replace(/[^\d]/g,'')" style="width:300px"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="sure">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <div class="dataTable">
      <el-table
        :data="officialStaffList.filter(data => !search || data.address.toLowerCase().includes(search.toLowerCase()))"
        style="width: 100%"
        :header-cell-style="{textAlign: 'center'}"
        :cell-style="{ textAlign: 'center' }"
        @select="selectBox"
      >
        <el-table-column
          type="selection"
          width="45"
        />
        <el-table-column
          label="员工id"
          prop="id"
          width="80">
        </el-table-column>
        <el-table-column
          label="Name"
          prop="name"
          width="80"
        />
        <el-table-column
          label="Age"
          prop="age"
          width="80"
          sortable
        />
        <el-table-column
          label="Gender"
          prop="gender"
          width="80"
        />
        <el-table-column
          label="Phone"
          prop="phone"
          width="120"
        />
        <el-table-column
          label="Address"
          prop="address"
          width="120"
        />
        <el-table-column
          label="EntryTime"
          prop="entryTime"
          sortable
          width="120"
        />
        <el-table-column
          label="Duty"
          prop="duty"
          width="80"
        />
        <el-table-column
          label="Salary"
          prop="salary"
          width="100"
          sortable
        />

        <el-table-column
          align="right"
        >
          <template slot="header" slot-scope="">
            <el-input
              v-model="search"
              size="mini"
              placeholder="输入地址"
            />
          </template>
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="handleEdit(scope)"
            >编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        style="float:right"
        layout="prev, pager, next"
        :total="total"
        :page-size="pageSize"
        :current-page.sync="page"
        @current-change="handlerChange"
      />
    </div>
  </div>
</template>

<script>
import interfaceList from '../../utils/interface'
export default {
  name: 'OfficialStaff',
  data() {
    return {
      pageSize:8,
      page:1,
      total:100,
      staffInput: '',
      search: '',
      dateTime:'',
      officialStaffList:[],
      StaffVisible:false,
      idAry:[],
      status:'',
      modalTitle:'',
      ruleForm: {
        name: '',
        age: '',
        gender: '男',
        phone: '',
        address: '',
        duty: '',
        salary: '',
      },
      rules: {
        name: [
          { required: true, message: '请输入员工姓名', trigger: 'blur' },
          { min: 2, message: '长度在 2个字符以上', trigger: 'blur' }
        ],
        age: [
          { required: true, message: '请输入员工年龄', trigger: 'blur' },
          { min: 1, max: 2, message: '要求输入1-2个数字', trigger: 'blur' },
        ],
        gender: [
            { required: true, message: '请选择性别', trigger: 'change' }
        ],
        phone: [
          { required: true, message: '请输入员工电话号码', trigger: 'blur' },
          { min: 11, max: 11, message: '要求输入11个数字', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入员工地址', trigger: 'blur' },
        ],
        duty: [
          { required: true, message: '请输入员工职位', trigger: 'blur' },
        ],
        salary: [
          { required: true, message: '请输入员工薪资', trigger: 'blur' },
          { min: 3,message: '要求输入3个以上的数字', trigger: 'blur' }
        ],
      },
      pickerOptions: {
        shortcuts: [{
        text: '最近一周',
        onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
        }
        }, {
        text: '最近一个月',
        onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
        }
        }, {
        text: '最近三个月',
        onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
        }
        }]
      },
    }
  },
  methods: {
    // 查询
    changeInput(val){
      // console.log(val)
      this.staffInput = val
      if(val === ''){
        this.getList()
      }
    },
    changeStaffName() {
      if(this.staffInput === ''){
        this.getList()
        return
      }
      // console.log(this.staffInput)
      interfaceList.searchOfficialStaffName({
        name:this.staffInput
      }).then(res =>{
        // console.log(res)
        if(res.code === 200){
          res.officialStaffNameList.forEach(item => {
            item.entryTime = this.formatDateTime(item.entryTime)
          })
          this.officialStaffList = res.officialStaffNameList
          this.total = this.officialStaffList.length
        }else{
          this.officialStaffList = res.officialStaffNameList
          this.total = this.officialStaffList.length
          this.$message(res.msg)
        }
      })
    },
    // 添加
    handleAdd(){
      // console.log(this.ruleForm)
      this.status = 'add'
      this.ruleForm = {
        name: '',
        age: '',
        gender: '男',
        phone: '',
        address: '',
        duty: '',
        salary: '',
      }
      this.modalTitle = '新增员工'
      this.StaffVisible = true
    },
    // 编辑
    handleEdit(data) {
      // console.log(data)
      // console.log(this.ruleForm)
      this.status = 'edit'
      this.ruleForm.id = data.row.id
      this.ruleForm.name = data.row.name
      this.ruleForm.age = data.row.age
      this.ruleForm.gender = data.row.gender
      this.ruleForm.address = data.row.address
      this.ruleForm.phone = data.row.phone
      this.ruleForm.entryTime = data.row.entryTime
      this.ruleForm.duty = data.row.duty
      this.ruleForm.salary = data.row.salary
      this.modalTitle = '编辑员工'
      this.StaffVisible = true
    },
    cancel(){
      if(this.status === 'add'){
        this.StaffVisible = false
        this.$refs.ruleForm.resetFields()
      }else{
        this.StaffVisible = false
      }
    },
    sure(){
      if(this.status === 'add') {
        interfaceList.addOfficialStaff(this.ruleForm).then(res =>{
          // console.log(res)
          if(res.code === 200){
            this.getList()
            this.$message({
              message: '添加成功',
              type: 'success'
            })
            this.$refs.ruleForm.resetFields()
          }else{
            this.$message.error(res.msg)
          }
        })
      }else{
        // console.log(this.ruleForm)
        interfaceList.updateOfficialStaff(this.ruleForm).then(res => {
          // console.log(res)
          if(res.code === 200) {
            this.getList()
            this.$message({
              message: '修改成功',
              type: 'success'
            })
          }else{
            this.$message.error(res.msg)
          }
        })
      }
      this.StaffVisible = false
    },
    // 删除
    handleDelete(data) {
      // console.log(data.row.id)
      this.$confirm('确定删除此员工吗?', '提示', {
        confirmButtonText: '确定' ,
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        interfaceList.delOfficialStaff(data.row.id).then(res =>{
          // console.log(res)
          if(res.code === 200) {
            this.page = 1
            this.getList()
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          }else{
            this.$message.error(res.msg)
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    selectBox(val){
      // console.log(val)
      val.forEach(item => {
        this.idAry.push(item.id)
      })
      // console.log([...new Set(this.idAry)])
    },
    batchDelete() {
      // console.log(this.idAry)
      if(this.idAry.length === 0){
        this.$message({
          message: '请先选择要删除的员工',
          type: 'warning'
        });
        return
      }
      this.$confirm('确定删除这些员工吗?', '提示', {
        confirmButtonText: '确定' ,
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        interfaceList.batchDelOfficialStaff({
          idAry:[...new Set(this.idAry)]
        }).then(res=> {
          // console.log(res)
          if(res.code === 200) {
            this.page = 1
            this.getList()
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          }else{
            this.$message.error(res.msg)
          }
      })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    searchDate(){
        console.log(this.dateTime)
        if(this.dateTime == null) {
          this.getList()
        }else{
          interfaceList.searchEntryStaffName({
            startTime: this.dateTime[0],
            endTime: this.dateTime[1]
          }).then(res=>{
            if(res.code === 200){
              this.total = res.officialStaffNameList.length
            }
          })

          interfaceList.pageSearchEntryStaffName({
            startTime: this.dateTime[0],
            endTime: this.dateTime[1],
            page:this.page,
            pageSize: this.pageSize
          }).then(res => {
            console.log(res)
            if(res.code === 200) {
              res.officialStaffNameList.forEach(item => {
                item.entryTime = this.formatDateTime(item.entryTime)
              })
              this.officialStaffList = res.officialStaffNameList
            } else{
              this.officialStaffList = res.officialStaffNameList
              this.$message.error(res.msg)
            }
          })
        }
    },
    // 格式化时间
    addZero(num) {
      return num < 10 ? '0' + num : num;
    },
    formatDateTime(date) {
      const time = new Date(Date.parse(date));
      time.setTime(time.setHours(time.getHours() + 8));
      const Y = time.getFullYear() + '-';
      const M = this.addZero(time.getMonth() + 1) + '-';
      const D = this.addZero(time.getDate()) + ' ';
      return Y + M + D;
    },
    // 分页
    handlerChange(val){
      // console.log(val)
      this.page = val
      if(this.dateTime !== ''){
        this.searchDate()
      }else{
        this.getList()
      }
    },
    getAllList(){
      interfaceList.getOfficialStaffList().then(res => {
        // console.log(res)
        if(res.code === 200) {
          // console.log(res.officialStaffList.length)
          this.total = res.officialStaffList.length
        }
      })
    },
    getList(){
      interfaceList.pagingOfficialStaffList({
        page:this.page,
        pageSize:this.pageSize
      }).then(res => {
        console.log(res)
        if(res.code === 200){
          res.officialStaffList.forEach(item => {
            item.entryTime = this.formatDateTime(item.entryTime)
          })
          this.officialStaffList = res.officialStaffList
          this.getAllList()
        }else{
          this.officialStaffList = res.officialStaffList
          // this.$message(res.msg)
        }
      })
    }
  },
  created(){
    this.getList()
  }
}
</script>

<style lang="scss" scoped>
.officialStaffBox{
    margin: 10px 0 0 10px;
    // background-color: green;
    .title{
        font-size: 22px;
        font-family: PingFangSC-Regular;
        color: #40404C;
        letter-spacing: 0.35px;
        line-height: 28px;
        border-bottom: 0.5px solid #B9B9B9;
        margin: 32px 0 20px 20px;
    }
    .btn{
        .input-with-select{
            width: 250px;
            height: 10px;
            margin-right: 30px;
        }
        .batchDelete{
            margin-right: 20px;
        }
    }
    .dataTable{
        margin-top: 30px;
    }
    .demo-ruleForm{
      position: relative;
      top: 0;
      left: 50px;
    }
}
</style>
